package com.dts.server.config;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.dts.server.common.annotation.Authority;
import com.dts.server.common.annotation.Expose;
import com.dts.server.common.enums.ResultCode;
import com.dts.server.common.exception.CustomException;

public class AuthInterceptor extends HandlerInterceptorAdapter {
	
    @Override
    @SuppressWarnings("unchecked")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//OPTIONS 方法不过滤
		if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        //验证是否具有访问接口的权限
		if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            HttpSession session = request.getSession();
            //检查是否需要登录
            if(!handlerMethod.hasMethodAnnotation(Expose.class)){
                if (session == null || session.getAttribute("account") == null) {
                    //登录超时
                    throw new CustomException(ResultCode.SESSION_INVALID);
                }
            }
            //检查是否需要访问权限
            if(handlerMethod.hasMethodAnnotation(Authority.class)){
                String auth = handlerMethod.getMethodAnnotation(Authority.class).value();
                if(session.getAttribute("auths")!=null){
                    List<String> auths = (List<String>)session.getAttribute("auths");
                    String[] vals = auth.split(",");
                    for(String val : vals){
                        if(auths.contains(val)){
                            return true;
                        }
                    }
                }
                //没有访问权限
                throw new CustomException(ResultCode.S_UNAUTH_ERROR);
            }
        }
        return true;
    }
	
}
